<!-- 统计面板 -->
<template>
  <div class="sa-block" v-show="isShowStatistics">
    <el-row style="font-size: 18px; color: black; padding: 8px;">
      <span>统计面板</span>
      <el-button style="position:absolute; right: 8px; top: 12px;" type="" link @click="toggleShowStatistics">
        <el-icon>
          <Close />
        </el-icon>
      </el-button>
      <el-divider style="margin: 1px 0; width: 95%" />
    </el-row>
    <el-row justify="center">
      <el-col :span="12">
        <el-statistic title="总栋数" :value="indexData.ds_sum ?? 0" />
      </el-col>
      <el-col :span="12">
        <el-statistic title="建筑总面积（万㎡）" :value="(indexData.zjzmj_sum / 10000).toFixed(2) ?? 0" />
      </el-col>
      <el-col :span="12">
        <el-statistic title="计算容积率建筑面积（万㎡）" :value="(indexData.jrjzmj_sum / 10000).toFixed(2) ?? 0" />
      </el-col>
      <el-col :span="12">
        <el-statistic title="总基底面积（万㎡）" :value="(indexData.jdmj_sum / 10000).toFixed(2) ?? 0" />
      </el-col>
      <el-col :span="12">
        <el-statistic title="最大地上层数" :value="indexData.cs_max ?? 0" />
      </el-col>
      <el-col :span="12">
        <el-statistic title="最大建筑高度" :value="indexData.lg_max ?? 0" />
      </el-col>
      <el-divider style="width: 95%" />
    </el-row>
    <el-row justify="center">
      <div style="width: 100%; height: 350px; position: relative;">
        <span v-if="!showChartByTime"
          style="width: 200px; position:absolute; top: -3px; left: 21.5px; font-weight: 700; font-size: 18px;">时间分布</span>
        <MutiYAxis v-show="showChartByTime" />
        <el-table :data="timeTableData"
          style="margin-left: 40px;top: 40px; width: 90%; height: 320px; overflow-y: auto;" v-show="!showChartByTime">
          <el-table-column prop="date" label="月份" width="180" />
          <el-table-column prop="ds" label="栋数（栋）" />
          <el-table-column prop="areas" label="总建筑面积（万㎡）" />
        </el-table>
        <el-select v-model="yearSelect" placeholder="Select" size="small"
          style="width: 80px; position:absolute; top: 0; right: 90px" @change="handleOnTimeChange">
          <el-option v-for="item in yearOptions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-button style="width: 10px; position:absolute; top: 0; right: 40px" text :icon="Document" circle
          @click="handleOnClick1" />
      </div>
      <el-divider style="width: 95%" />
    </el-row>
    <el-row justify="center">
      <div style="width: 100%; height: 375px; position: relative; ">
        <span v-if="!showChartByZJ"
          style="width: 200px; position:absolute; top: -3px; left: 21.5px; font-weight: 700; font-size: 18px;">区域分布</span>
        <BYMap v-show="showChartByZJ" />
        <el-table :data="zjTableData" style="margin-left: 40px;top: 40px; width: 90%; height: 340px; overflow-y: auto;"
          v-show="!showChartByZJ">
          <el-table-column prop="name" label="街镇" width="180" />
          <el-table-column prop="value" :label="store.mapDataKey === 'areas' ? '总建筑面积（万㎡）' : '栋数'" />
        </el-table>
        <div style="position: absolute; top: 0; right: 100px;">
          <el-radio-group v-model="mapStatisType" size="small" @change="handleOnRatioChange">
            <el-radio-button label="总建筑面积" value="总建筑面积" />
            <el-radio-button label="栋数" value="栋数" />
          </el-radio-group>
        </div>
        <el-button style="width: 10px; position:absolute; top: 0; right: 40px" text :icon="Document" circle
          @click="handleOnClick2" />
      </div>
      <el-divider style="width: 95%" />
    </el-row>
    <el-row justify="center">
      <span v-if="!showChartByGn"
        style="width: 200px; position:absolute; top: -3px; left: 21.5px; font-weight: 700; font-size: 18px;">主要功能建筑面积</span>
      <div style="width: 100%; height: 350px;padding-right: 20px">
        <BYPie v-show="showChartByGn" />
        <el-table :data="gnTableData" style="margin-left: 40px;top: 40px; width: 90%; height: 320px; overflow-y: auto;"
          v-show="!showChartByGn">
          <el-table-column prop="name" label="功能类型" width="180" />
          <el-table-column prop="value" label="建筑面积（万㎡）" />
        </el-table>
        <el-button style="width: 10px; position:absolute; top: 0; right: 40px" text :icon="Document" circle
          @click="handleOnClick3" />
      </div>
      <el-divider style="width: 95%" />
    </el-row>
    <el-row justify="center">
      <span v-if="!showChartByHeight"
        style="width: 200px; position:absolute; top: -3px; left: 21.5px; font-weight: 700; font-size: 18px;">建筑高度分布</span>
      <div style="width: 68%; height: 300px;" v-show="showChartByHeight">
        <BYHeightAreasPie />
      </div>
      <div style="width: 32%; height: 300px;" v-show="showChartByHeight">
        <BYHeightCountPie />
      </div>
      <el-table :data="heightTableData" style="height: 260px; margin-top: 40px;" v-show="!showChartByHeight">
        <el-table-column prop="lg" label="类型" width="180" />
        <el-table-column prop="areas" label="总建筑面积（万㎡）" />
        <el-table-column prop="ds" label="栋数" />
      </el-table>
      <el-button style="width: 10px; position:absolute; top: 0; right: 40px" text :icon="Document" circle
        @click="handleOnClick4" />
      <el-divider style="width: 95%" />
    </el-row>
    <el-row justify="center">
      <div style="width: 100%; height: 400px; position: relative;">
        <span v-if="!showChartByLayer"
          style="width: 200px; position:absolute; top: -3px; left: 21.5px; font-weight: 700; font-size: 18px;">地上层数统计</span>
        <BYlayersBar v-show="showChartByLayer" />
        <el-table :data="layerTableData" style="top: 40px; height: 385px;" v-show="!showChartByLayer">
          <el-table-column prop="name" label="地上层数" width="180" />
          <el-table-column prop="value" :label="store.layerDataKey === 'areas' ? '总建筑面积（万㎡）' : '栋数'" />
        </el-table>
        <div style="position: absolute; top: 0; right: 100px;">
          <el-radio-group v-model="layerStatisType" size="small" @change="handleOnLayerChange">
            <el-radio-button label="总建筑面积" value="总建筑面积" />
            <el-radio-button label="栋数" value="栋数" />
          </el-radio-group>
        </div>
        <el-button style="width: 10px; position:absolute; top: 0; right: 40px" text :icon="Document" circle
          @click="handleOnClick5" />
        <el-divider style="width: 95%" />
      </div>
    </el-row>
  </div>
</template>

<script setup>
import { Close, Document } from '@element-plus/icons-vue';
import { useStore } from '@/store/useStore';
import { storeToRefs } from 'pinia';
import { ref, onMounted, watch } from 'vue';
import MutiYAxis from '@/components/MutiYAxis.vue';
import BYMap from '@/components/BYMap.vue';
import BYPie from '@/components/BYPie.vue';
import BYHeightAreasPie from '@/components/BYHeightAreasPie.vue';
import BYHeightCountPie from '@/components/BYHeightCountPie.vue';
import BYlayersBar from '@/components/BYlayersBar.vue';
import { getProjectResultIndex, getYearsForWcsj, getMonthCountForDs, getMonthCountForZjzmj, getZygnGroupCount, getCountByDistrict, getZjzmjCountGroupByLg, getZjzmjCountGroupByCs } from '@/api/dataApi';

const store = useStore();
const { isShowStatistics } = storeToRefs(store);
const { toggleShowStatistics } = store;

// 指标统计
const indexData = ref({});
const loadDataByIndex = async () => {
  await getProjectResultIndex(store.searchParams).then((res) => {
    const data = res.data.data;
    indexData.value = data;
  });
};

// 按完成时间统计
const yearOptions = ref([])
const yearSelect = ref(2024)
const showChartByTime = ref(true);
const loadDataByTime = async () => {
  await getYearsForWcsj(store.searchParams).then((res) => {
    yearOptions.value = res.data.data;
    yearSelect.value = yearOptions.value[0];
  });
  await getMonthCountForDs({ ...store.searchParams, year: yearSelect.value }).then(res => {
    store.$patch({ dsByTime: res.data.data.map(item => item.value) })
  })
  await getMonthCountForZjzmj({ ...store.searchParams, year: yearSelect.value }).then(res => {
    store.$patch({ areasByTime: res.data.data.map(item => item.value) })
  })
  loadDataByTimeTable();
}

const handleOnTimeChange = async () => {
  await getMonthCountForDs({ ...store.searchParams, year: yearSelect.value }).then(res => {
    store.$patch({ dsByTime: res.data.data.map(item => item.value) })
  })
  await getMonthCountForZjzmj({ ...store.searchParams, year: yearSelect.value }).then(res => {
    store.$patch({ areasByTime: res.data.data.map(item => item.value) })
  })
  loadDataByTimeTable();
}

const timeTableData = ref([]);

const loadDataByTimeTable = () => {
  timeTableData.value = store.dsByTime.map((item, index) => ({
    date: (index + 1) + '月',
    ds: item,
    areas: (store.areasByTime[index] / 10000).toFixed(2)

  }));
}
const handleOnClick1 = () => {
  showChartByTime.value = !showChartByTime.value;
}

// 按镇街统计
const mapStatisType = ref('总建筑面积');
const showChartByZJ = ref(true);
const handleOnRatioChange = (val) => {
  if (val === '栋数') {
    store.$patch({ mapDataKey: 'ds' });
  } else {
    store.$patch({ mapDataKey: 'areas' });
  }
  zjTableData.value = store.mapDataKey === 'areas' ? store.mapByData.areas.map(item => ({ name: item.name, value: (item.value / 10000).toFixed(2) })) : store.mapByData.ds;
}

const zjTableData = ref([]);

const loadDataByZJ = async () => {
  await getCountByDistrict(store.searchParams).then(res => {
    store.$patch({
      mapByData: {
        areas: res.data.data.map(item => ({ name: item.town_name, value: item.zjzmj_sum ?? 0 })),
        ds: res.data.data.map(item => ({ name: item.town_name, value: item.ds_sum ?? 0 }))
      },
      mapDataKey: 'areas'
    })
  })
  zjTableData.value = store.mapDataKey === 'areas' ? store.mapByData.areas.map(item => ({ name: item.name, value: (item.value / 10000).toFixed(2) })) : store.mapByData.ds;
}

const handleOnClick2 = () => {
  showChartByZJ.value = !showChartByZJ.value;
}

// 按主要功能统计

const showChartByGn = ref(true);
const gnTableData = ref([]);
const loadDataByGn = async () => {
  await getZygnGroupCount(store.searchParams).then((res) => {
    var data = res.data.data.filter(item => item.value !== 0);
    store.$patch({ dataByGn: data.map(item => ({ name: item.key, value: item.value })) })
  });
  gnTableData.value = store.dataByGn.map(item => ({ name: item.name, value: (item.value / 10000).toFixed(2) }));
}

const handleOnClick3 = () => {
  showChartByGn.value = !showChartByGn.value;
}

// 按建筑高度统计
const showChartByHeight = ref(true);
const heightTableData = ref([]);

const loadDataByHeight = async () => {
  await getZjzmjCountGroupByLg(store.searchParams).then((res) => {
    // console.log(res.data.data,"sy111");
    if(res.data.data){
      res.data.data[0].lg_type = "≤24米"
      res.data.data[1].lg_type = "(24, 60]米"
      res.data.data[2].lg_type = "(60, 80]米"
      res.data.data[3].lg_type = "(80, 100]米"
      res.data.data[4].lg_type = "＞100米"
    }
    store.$patch({
      areasByHeight: res.data.data.map(item => ({ name: item.lg_type, value: item.key.toFixed(2) })),
      dsByHeight: res.data.data.map(item => ({ name: item.lg_type, value: item.value }))
    });
  });

  heightTableData.value = store.areasByHeight.map((item, index) => ({
    lg: item.name,
    areas: (item.value / 10000).toFixed(2),
    ds: store.dsByHeight[index].value
  }));
}

const handleOnClick4 = () => {
  showChartByHeight.value = !showChartByHeight.value;
}

// 按地上层数统计
const layerStatisType = ref('总建筑面积');
const showChartByLayer = ref(true);
const layerTableData = ref([]);
const loadDataByLayer = async () => {
  await getZjzmjCountGroupByCs(store.searchParams).then((res) => {
    store.$patch({
      layerByData: {
        areas: res.data.data.map(item => ({ name: item.cs_type, value: item.value })),
        ds: res.data.data.map(item => ({ name: item.cs_type, value: item.key }))
      },
      layerDataKey: 'areas',
    });
  });
  loadLayerTable();
}
const loadLayerTable = () => {
  layerTableData.value = store.layerDataKey === 'areas' ? store.layerByData.areas.map(item => ({ name: item.name, value: (item.value / 10000).toFixed(2) })) : store.layerByData.ds;
  const sortOrder = ['低层', '多层', '中高层', '高层'];
  const orderMap = new Map(sortOrder.map((type, index) => [type, index]));
  layerTableData.value.sort((a, b) => orderMap.get(a.name) - orderMap.get(b.name));
  const replaceRule = {
    '低层': '低层（1~3层）',
    '多层': '多层（4~6层）',
    '中高层': '中高层（7~9层）',
    '高层': '高层（10层及以上）'
  };
  layerTableData.value.forEach(item => {
    if (replaceRule[item.name]) {
      item.name = replaceRule[item.name];
    }
  });
}

const handleOnClick5 = () => {
  showChartByLayer.value = !showChartByLayer.value;
}

const handleOnLayerChange = (val) => {
  if (val === '栋数') {
    store.$patch({ layerDataKey: 'ds' });
  } else {
    store.$patch({ layerDataKey: 'areas' });
  }
  loadLayerTable();
}


/**
 * 加载数据的函数
 *
 * 调用多个函数以加载不同类型的数据
 */
const loadData = () => {
  loadDataByTime();
  loadDataByGn();
  loadDataByZJ();
  loadDataByHeight();
  loadDataByLayer();
  loadDataByIndex();
}

watch(() => store.searchParams, () => {
  loadData()
}, { deep: true })

watch(isShowStatistics, (val) => {
  if (val) {
    loadData();
  }
})

onMounted(() => {
  // loadData();
})
</script>

<style scoped>
.sa-block {
  z-index: 2002;
  position: fixed;
  right: 0;
  top: 0;
  height: 100%;
  width: 550px;
  background-color: white;
  overflow-y: auto;
  overflow-x: hidden;
}

.el-col {
  padding-top: 20px;
  text-align: center;
}
</style>

<style>
.el-statistic__number {
  font-size: 24px;
  font-weight: 600;
}
</style>
